package logic

import (
	"context"
	"errors"
	"furni-set/models/mysql"

	"furni-set/funrpc/funrpc"
	"furni-set/funrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type FruitAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFruitAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FruitAddLogic {
	return &FruitAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FruitAddLogic) FruitAdd(in *funrpc.FruitAddRequest) (*funrpc.FruitAddResponse, error) {
	// todo: add your logic here and delete this line

	//防止重复水果商品同名，
	var fruits mysql.Fruit
	if err := fruits.FindFruit(mysql.DB, in.FruitName); err == nil {
		return nil, errors.New("水果商品已存在不能再次添加")
	}

	begin := mysql.DB.Begin()
	//13、如果分类不存在的时候进行添加,如果存在不添加
	sort := mysql.Sort{
		Model:    gorm.Model{},
		SortName: in.SortName,
	}
	if err := sort.SortFind(mysql.DB, in.SortName); err != nil {
		begin.Rollback()
		return nil, err
	}
	//12、如果品牌不存在进行添加,如果品牌存在的不添加
	brands := mysql.Brand{
		Model:     gorm.Model{},
		BrandName: in.BrandName,
	}
	if err := brands.BrandFindName(mysql.DB, in.BrandName); err != nil {
		begin.Rollback()
		return nil, err
	}
	//11、添加时需添加家具的分类以及品牌,添加的时候需要输入品牌名称及分类名称
	fruit := &mysql.Fruit{
		Model:      gorm.Model{},
		FruitName:  in.FruitName,
		FruitPrice: float64(in.FruitPrice),
		FruitNum:   in.FruitNum,
		BrandId:    int64(brands.ID),
		SortId:     int64(sort.ID),
	}
	if err := fruit.FruitAdd(mysql.DB); err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &funrpc.FruitAddResponse{
		FruitsId: int64(fruit.ID),
	}, nil
}
